from functools import wraps
from flask import g, request, redirect, url_for,abort
from ..redis import rd
import json
from ..models.database import db
from ..models.console.menu import Menu
from ..models.common.log import Log

def console_token(f):
    @wraps(f)
    def check_token(*args, **kwargs):
        return f(*args, **kwargs)
        # token 判断
        token = request.headers.get('token')
        data = request.values.to_dict()
        # 权限判断
        current_url = request.path
        url_list = str(current_url).split('/')
        for i in url_list:
            if i == '':
                url_list.remove('')
        # print('### url ###', url_list)
        url1 = url_list[0] if len(url_list) > 0 else None
        if url1 != 'c-api':
            return {'message': '无权调用此接口数据...'},402
        # 除登录外，都验证 token
        admin = {}
        priv = None
        p1 = url_list[1] if len(url_list) > 1 else 'None'
        if p1 == 'login':
            # get 请求外的记录日志
            if request.method != 'GET':
                c = Log(admin_id=0, method=request.method, url=request.url, action_name='用户登录', user=request.values.get('admin_name'), data=json.dumps(data))
                db.session.add(c)
        else:
            if rd.exists('c-token:' + token) == False:
                return {'message': '验证信息无效，请重新登录'}, 401
            admin = json.loads(rd.get('c-token:' + token))
            p2 = url_list[2] if len(url_list) > 2 else 'None'
            priv = p1 + '-' + p2
            print('### 当前用户 ###', admin)
            allPriv = admin.get('allPriv')
            # 权限逻辑，除登录外，超级管理员外，验证 priv list 里有没有
            if 1 in admin.get('allRole') or priv in allPriv.keys():
                # get 请求外的记录日志
                if request.method != 'GET':
                    c = Log(admin_id=admin.get('id'), method=request.method, url=request.url,
                            action_name=allPriv.get(priv,'未找到名称'), user=admin.get('name'), data=json.dumps(data))
                    db.session.add(c)
            else:
                return {'message':'无权调用此接口数据'},402
        return f(*args, **kwargs)
    return check_token
